/*
 * @Author: FlowerGuest flowers.guests@gmail.com
 * @Date: 2025-08-27 21:12:39
 * @LastEditors: FlowerGuest flowers.guests@gmail.com
 * @LastEditTime: 2025-11-18 21:15:50
 * @FilePath: \zhuzhou\src\router\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/index",
    component: () => import("@/pages/home/index.vue"),
    meta: {
      type: "index",
      title: "首页",
    },
    children: [],
  },
  {
    path: "/multiple-analysis-reports",
    name: "MultipleAnalysisReports",
    component: () => import("@/pages/analysis/multiple-analysis-reports.vue"),
    meta: {
      title: "事故多项分析",
    },
    children: [],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/pages/login/index.vue"),
    meta: {
      title: "登录",
    },
    children: [],
  },
  {
    path: "/aiModel",
    name: "aiModel",
    component: () => import("@/pages/aimodel/index.vue"),
    meta: {
      title: "ai",
    },
    children: [],
  },
];

import { useLogin, jurisdiction } from "@/store";

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

// 全局前置守卫：刷新时从localStorage获取token并同步到状态管理
router.beforeEach((to, from, next) => {
  console.log(from);

  const storedUser = localStorage.getItem("userInfo");
  const login = useLogin();
  const jur = jurisdiction();
  if (storedUser) {
    const { expires, ...userData } = JSON.parse(storedUser);
    if (Date.now() < expires) {
      login.setState(userData);
      jur.setSex(userData.user);
      jur.setState(userData.activeMenuArray);
      if (login.access_token) {
        next();
        return;
      } else {
        if (to.path !== "/login") {
          next({ path: "/login" });
          return;
        }
      }
    } else {
      localStorage.removeItem("userInfo");
    }
  } else {
    // 未登录时，若不在登录页则跳转
    if (to.path !== "/login") {
      next({ path: "/login" });
      return;
    }
  }
  next();
});

export default router;
